﻿using UnityEngine;
using System.Collections;

public class GameController
{
	public Army mArmy;
	public LevelsConfig mLevelConfig;
	public IconSetupper iconSetupper;

	public Monster mMonster;
	public int HP;
	public uint mKilledCount;
	public int CurrentLevel;
	public int MaxAvailableLevel;

	public UITexture StageTexture;
	public UITexture MonsterTexture;
	public UIProgressBar HPProgressBar;
	public UILabel HPLabel;

	UIController mUICtrl;

	public GameController()
	{
		mArmy = new Army();
		mLevelConfig = new LevelsConfig();
		iconSetupper = new IconSetupper();
		mUICtrl = new UIController(this);

		CurrentLevel = 0;
		MaxAvailableLevel = -1;

		StageTexture = GameObject.FindWithTag("Stage").GetComponent<UITexture>();
		MonsterTexture = GameObject.FindWithTag("Monster").GetComponent<UITexture>();
		HPProgressBar = GameObject.FindWithTag("HPProgressBar").GetComponent<UIProgressBar>();
		HPLabel = GameObject.FindWithTag("HPLabel").GetComponent<UILabel>();

		StepToLevel(0);

		NextMonster();
	}

	public void OnGUI()
	{
		mUICtrl.OnGUI();
	}

	public void Update(float deltaTime)
	{
		int attackPower = mArmy.AttackPower();

		HP -= attackPower;
		//Debug.Log("HP = " + HP);

		if (HP < 0){
			mKilledCount++;
			if (mKilledCount >= mLevelConfig.Levels[CurrentLevel].UnlockCount)
			{
				if (CurrentLevel + 1 > MaxAvailableLevel)
				{
					StepToLevel(CurrentLevel + 1);
				}
			}
			NextMonster();
		}

		float percent = HP*1.0f/mMonster.HP;
		//Debug.Log("percent = " + percent);
		HPProgressBar.value = percent;

		HPLabel.text = HP.ToString() + " HP"; 
	}

	public void NextMonster()
	{
		int monsterCount = mLevelConfig.Levels[CurrentLevel].Monsters.Count;
		int index = Random.Range(0, monsterCount);

		mMonster = mLevelConfig.Levels[CurrentLevel].Monsters[index];
		HP = mMonster.HP;

		Texture mT = Resources.Load(mMonster.TexturePath) as Texture;
		DebugUtil.Assert(mT != null);
		MonsterTexture.mainTexture = mT;
	}

	public void StepToLevel(int index)
	{
		CurrentLevel = index;
		mKilledCount = 0;

		if (index > MaxAvailableLevel)
		{
			MaxAvailableLevel = index;
			iconSetupper.SetupLevelIcon(index, mLevelConfig.Levels[index].IconTexturePath);
		
			string stageTexPath = mLevelConfig.Levels[index].StageTexturePath;
			Texture stageTex = Resources.Load(stageTexPath) as Texture;
			DebugUtil.Assert(stageTex != null, "StageTexturePath: "+stageTexPath+" Not Exist.");
			StageTexture.mainTexture = stageTex;
		}
	}
}

